/*
 * @Description:
 * @Author: zhougang
 * @Date: 2025-07-07 10:19:00
 * @LastEditors: zhougang
 * @LastEditTime: 2025-07-18 11:24:56
 */
import { defineConfig, loadEnv } from "vite";
import devProxy from "./devProxy.ts";

import vueJsx from "@vitejs/plugin-vue-jsx";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import { visualizer } from "rollup-plugin-visualizer";
// import UnoCss from "unocss/vite";
import VueDevTools from "vite-plugin-vue-devtools";

import path from "path";

// console.log('node-env: ', import.meta.env.NODE_ENV)

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), ["VITE_", "DB_"]);
  // const env = loadEnv(mode, process.cwd());
  console.log("define config: ", env);

  return {
    base: mode === "production" ? "/" : "./", // 正常? '/my-app' : './'
    optimizeDeps: {
      // force: true,
      include: ["pinia", "lodash-es", "axios", "@vueuse/core", "dayjs"],
      exclude: ["lodash"],
    },
    build: {
      target: "es2015",
      rollupOptions: {
        output: {
          manualChunks: {
            "vue-vendor": ["vue", "vue-router", "pinia", "axios"],
            // "ui-library": ["@smallwei/avue", "element-plus"],
            "ui-library": ["element-plus"],
            // "ui-library": ["element-plus"],
          },
          // chunkFileNames: "static/js/[name]-[hash].js",
          chunkFileNames: (chunkInfo) => {
            const { name, facadeModuleId = null } = chunkInfo;
            // console.log("name: ", name, name.startsWith("el-"));
            if (name === "index") {
              if (facadeModuleId?.includes("views/")) {
                let viewName = facadeModuleId.match(/views\/(.*?)\.vue/)?.[1]?.replace(/\//g, "-");
                return `static/js/view-${viewName || "unknow"}-[hash].js`;
              } else if (facadeModuleId?.includes("components/")) {
                let compName = facadeModuleId
                  .match(/components\/(.*?)\.vue/)?.[1]
                  ?.replace(/\//g, "-");
                return `static/js/comp-${compName || "unknow"}-[hash].js`;
              } else {
                return "static/js/misc-[hash].js";
              }
            }
            return `static/js/${name}-[hash].js`;
          },
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
        },
      },
      outDir: "dist",
      assetsDir: "static",
      emptyOutDir: true,
      chunkSizeWarningLimit: 800,
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },
    server: { port: 9999, proxy: devProxy },
    preview: { proxy: devProxy },
    css: {
      preprocessorOptions: {
        scss: {
          // api: "modern-compiler",
          additionalData: `@use "@/styles/variables.scss" as vars;`,
        },
      },
    },
    plugins: [
      vue(),
      VueDevTools(), // 代替浏览器的 vue.js devtools插件
      vueJsx(),
      visualizer({
        open: true,
        filename: "bundle-stats.html",
      }),
      // UnoCss(),
      AutoImport({
        resolvers: [
          ElementPlusResolver({ importStyle: "sass" }),
          IconsResolver({ prefix: "Icon" }),
        ],
        imports: [
          "vue",
          "vue-router",
          "pinia",
          {
            "@/utils/func.ts": ["sleep", "range"],
            "@/utils/tip/message.ts": [["*", "tipUtils"]],
            "@/utils/toolsfunc.ts": [["*", "toolsfunc"]],
          },
        ],
        dts: true,
        eslintrc: {
          enabled: true,
        },
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({ enabledCollections: ["ep", "mdi", "lucide"], prefix: "i" }),
        ],
        dts: true,
        dirs: ["src/components"],
        include: [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/, /\.jsx?$/, /\.tsx?$/, /\.svg$/],
        globs: ["src/components/**/*.vue", "!src/components/**/modules/*.vue"],
        extensions: ["vue"],
        deep: true,
      }),
      Icons({
        autoInstall: true,
        compiler: "vue3",
      }),
    ],
  };
});
